package com.ssl.basics.thread.incre;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/13 0013.
 */
public class ThreadIncreDemo5 {
    static class ValueEntity {
        private int sum;

        private static Unsafe unsafe;
        private static long sum_offset;

        static {
            try {
                Field field = Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                unsafe = (Unsafe) field.get(null);
                sum_offset = unsafe.objectFieldOffset(ValueEntity.class.getDeclaredField("sum"));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        public void incre() {
            unsafe.getAndAddInt(this, sum_offset, 1);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int threadSize = 10;
        CountDownLatch latch = new CountDownLatch(threadSize);

        ValueEntity entity = new ValueEntity();

        for (int i = 0; i < threadSize; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    entity.incre();
                }
                latch.countDown();
            }, String.valueOf(i)).start();
        }

        latch.await();
        System.out.println(entity.sum);

    }
}
